#pragma once
#include <iostream>
#include <memory>
#include <atomic>
#include <print>
#include <chrono>
#include <thread>

#include <cstdio>

#include <Python.h>

#include <boost/asio.hpp>
#include <boost/asio/ssl.hpp>
#include <nlohmann/json.hpp>

#include <yaml-cpp/yaml.h>


#include "sensorcollection.h"

// 线程函数声明
void run_media_python();
void run_transmission_client(const std::string& config_path);

struct EvaluateStatus {
    bool done = false;
    bool has_3d = false;
    bool has_slices = false;
};

class SensorHTTPServer
{
private:
    SensorCollection sensor_collection;
    std::atomic<bool> is_running{ true };
    std::mutex log_mutex;
    boost::asio::ip::tcp::acceptor* acceptor{ nullptr };

    // Python线程
    std::thread media_thread;
    std::thread transmission_thread;

    void log(const std::string& msg) {
        std::lock_guard<std::mutex> lock(log_mutex);
        auto now = std::chrono::system_clock::now();
        std::time_t now_time = std::chrono::system_clock::to_time_t(now);
        std::println("[time = {}, msg = {}]", std::ctime(&now_time), msg);
    }

    // 解析HTTP请求
    std::string parse_http_request(const std::string& request);

    // 处理HTTP请求并生成响应
    std::string handle_http_request(const std::string& path, const std::string& body);

    // 处理客户端连接
    void handle_client(boost::asio::ip::tcp::socket& client);

    // 加载配置
    void load_config(const std::string& config_path);

    // 生成HTTP响应
    std::string create_http_response(int status_code, const std::string& content, const std::string& content_type = "application/json");

    HANDLE hPipe{ INVALID_HANDLE_VALUE };  // 管道句柄
    std::thread pipe_listener_thread;      // 监听线程
    std::atomic<bool> pipe_running{ false }; // 管道运行状态
    std::mutex pipe_mutex;                 // 管道操作互斥锁

    static constexpr auto PIPE_NAME = L"\\\\.\\pipe\\sensor_server_pipe";
    static constexpr int BUFFER_SIZE = 4096;

    // 管道监听函数（接收Python消息）
    void pipe_listener();

    // 处理Python消息
    void handle_python_message(const std::string& msg);

    // 启动Python进程（作为管道客户端）
    bool start_python_client(const std::string& script_path);

    // Transmission专用管道
    static constexpr auto TRANSMISSION_PIPE_NAME = L"\\\\.\\pipe\\transmission_pipe";
    HANDLE hTransmissionPipe{ INVALID_HANDLE_VALUE };
    std::thread transmission_pipe_thread;
    std::atomic<bool> transmission_pipe_running{ false };
    std::mutex transmission_pipe_mutex;

    EvaluateStatus eval_status;
    std::mutex eval_status_mutex;

    nlohmann::json cached_3d_data;
    std::mutex cached_3d_mutex;

    nlohmann::json cached_slices_data;
    std::mutex cached_slices_mutex;

    nlohmann::json modbus_query_result;  // 缓存查询结果
    std::mutex modbus_query_mutex;       // 线程锁

public:
    std::string host;
    uint16_t port;

public:
    SensorHTTPServer(const std::string& config_path = "config/port.yaml") {
        load_config(config_path);

        if (!Py_IsInitialized()) {
            Py_Initialize();
            // 若需要导入模块，还需设置 Python 路径
            PyRun_SimpleString("import sys");
            PyRun_SimpleString("sys.path.append('./')"); // 添加当前目录到模块搜索路径
        }

        init_pipe_communication("modbus.py");

        start_python_threads();
        std::println("SensorHTTPServer 构造函数执行完毕");
    }

    ~SensorHTTPServer() {
        stop();
        close_pipe_communication();          // 关闭modbus管道
        close_transmission_pipe();           // 关闭transmission管道
        if (acceptor != nullptr) {
            delete acceptor;
        }
        if (media_thread.joinable()) {
            media_thread.join();
        }
        if (transmission_thread.joinable()) {
            transmission_thread.join();
        }
        Py_Finalize();
    }

    // 启动Python相关线程
    void start_python_threads();

    // 启动HTTP服务端
    void start();

    // 停止服务端
    void stop();

public:
    // 发送消息到Python
    void send_to_python(const std::string& data);

    // 初始化管道通信
    bool init_pipe_communication(const std::string& python_script);

    // 关闭管道通信
    void close_pipe_communication();

    // 初始化Transmission管道
    bool init_transmission_pipe();

    // 关闭Transmission管道
    void close_transmission_pipe();

    // Transmission管道监听线程
    void transmission_pipe_listener();

    // 处理Transmission消息
    void handle_transmission_message(const std::string& msg);

    void send_to_transmission(const std::string& data);

};